fastapi-postgresql-boilerplate
·362 words·2 mins
Table of Contents
Detail codes on Github
Overview #
๐ FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python-type hints.
I made and used this boilerplate for projects that I’m working on. ๐งโ๐ป
it was powerful for building data-driven applications using schema for data validation, serialization, and documentation. ๐
Description #
A boilerplate that can serve as a base for FastAPI with PostgreSQL
Made with FastAPI, PostgreSQL, Docker, Coverage, SQLAlchemy, Pytest, Black, Flake8, Isort,
and Poetry.
Features #
Developer experience #
- ๐ Python 3.10 for programming language
- ๐ FastAPI for handling HTTP requests and responses
- ๐ณ Docker for containerization
- ๐ PostgreSQL for database
- ๐ฆ Poetry for dependency management
- ๐ Coverage for code coverage
- ๐งช Pytest for unit and integration testing
- ๐พ SQLAlchemy ORM for interacting with a database
- ๐ง Flake8 for linting
- ๐จ Black for code formatting
- ๐ Isort for sorting imports
Back-end app features #
- ๐ซ JWT authentication for secure access to the API
- ๐ข Layered architecture. (Controller, Service, Repository, Model)
- ๐ฆ Dependency injection for better code organization
- ๐ Swagger and Redoc for API documentation and testing
- โป๏ธ Schema validation for input and output data
Requirements #
- Python 3.10
- Poetry
- PostgreSQL
- Docker
Getting Started #
Every command below except build
and run
is executed in a docker container.
Set Environment Variables #
# Copy service env file
$ cp .env.example .env
# Copy db env file
$ cp .db.env.example .db.env
Build and run the app with Docker Compose #
# Build docker image
$ docker-compose build
# Run the app in the background
$ docker-compose up -d
# Watch logs
$ docker-compose logs -f
# Execute a command in a running container
$ docker-compose exec app <command>
Migrate database #
before test or use the app, you need to migrate the database.
# init User table
$ docker-compose exec app poetry run alembic upgrade head
Test #
# Run unit tests using pytest
$ docker-compose exec app poetry run pytest
Lint and format #
# Run flake8
$ docker-compose exec app poetry run flake8
# Run black
$ docker-compose exec app poetry run black .
# Run isort
$ docker-compose exec app poetry run isort .
What’s next? #
- Handle scheduled tasks with Celery